package com.flyco.modules.fms.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.util.DateUtils;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.fms.service.IFmsFeeInputService;
import com.flyco.modules.fms.vo.FmsReportVO;
import com.flyco.modules.oms.entity.OmsOrder;
import com.flyco.modules.stm.service.IStmOrderItemGrossProfitService;
import com.flyco.modules.stm.service.IStmOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 费用报表
 * @Author: flyco
 * @Date: 2021-03-02
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "费用报表")
@RestController
@RequestMapping("/f/fms/fmsReport")
public class FmsReportController {

    @Autowired
    private IStmOrderService stmOrderService;
    @Autowired
    private IFmsFeeInputService feeInputService;
    @Autowired
    private IStmOrderItemGrossProfitService stmOrderItemGrossProfitService;

    /**
     * 费用统计
     *
     * @return
     */
    @ApiOperation(value="报表-费用统计", notes="报表-费用统计")
    @GetMapping(value = "/getFmsReport")
    public Result<?> getFmsReport(@RequestParam(name="startTime",required=true) String startTime,
                                  @RequestParam(name="endTime",required=true) String endTime) {
        if (oConvertUtils.isEmpty(startTime) || oConvertUtils.isEmpty(endTime)) return Result.error("开始时间或结束时间为空");
        log.info("FmsReport startTime: " + startTime);
        log.info("FmsReport endTime: " + endTime);
        startTime = startTime.replace("\"", "").substring(0, 10);
        endTime = endTime.replace("\"", "").substring(0, 10);
        //Date dayStart = DateUtils.getStartDay(DateUtils.getYear(startTime),DateUtils.getMonth(startTime));
        //Date dayEnd = DateUtils.getLastDay(DateUtils.getYear(endTime),DateUtils.getMonth(endTime));
        log.info("FmsReport getMonth: " + DateUtils.getMonth(DateUtils.str2Date(endTime,DateUtils.date_sdf.get())));
        Date dayStart = DateUtils.getStartDay(DateUtils.getYear(DateUtils.str2Date(startTime,DateUtils.date_sdf.get())),DateUtils.getMonth(DateUtils.str2Date(startTime,DateUtils.date_sdf.get())));
        Date dayEnd = DateUtils.getLastDay(DateUtils.getYear(DateUtils.str2Date(endTime,DateUtils.date_sdf.get())),DateUtils.getMonth(DateUtils.str2Date(endTime,DateUtils.date_sdf.get()))+1);
        log.info("FmsReport dayStart: " + dayStart);
        log.info("FmsReport dayEnd: " + dayEnd);
        //销售收入
        List<FmsReportVO> vos = stmOrderService.getFmsReport(dayStart,dayEnd);
        vos.forEach(r->{
            r.setCategoryId(0L);
            r.setCategoryType("IN");
            r.setCategoryName("营业收入");
        });
        //商品成本（按商品销售当天的成本价计算）
        List<FmsReportVO> grossProfitVos = stmOrderItemGrossProfitService.getFmsReport(dayStart,dayEnd);
        grossProfitVos.forEach(r->{
            r.setCategoryId(0L);
            r.setCategoryType("OUT");
            r.setCategoryName("采购成本");
        });
        vos.addAll(grossProfitVos);
        //费用录入支出
        List<FmsReportVO> feeVos = feeInputService.getFmsReport(dayStart,dayEnd);
        vos.addAll(feeVos);
        vos.forEach(vo->{
            if (Objects.equals("OUT", vo.getCategoryType())) {
                vo.setAmount(vo.getAmount().negate());
            }
        });
        List<FmsReportVO> totalList = new ArrayList<>();
        Map<Long,List<FmsReportVO>> voMap = vos.stream().collect(Collectors.groupingBy(e -> e.getStoreId()));
        voMap.entrySet().forEach(itemEntry -> {
            List<FmsReportVO> list = itemEntry.getValue();
            FmsReportVO totalVo = new FmsReportVO();
            totalVo.setStoreId(itemEntry.getKey());
            totalVo.setStoreName(list.get(0).getStoreName());
            totalVo.setCategoryId(Long.MAX_VALUE);
            totalVo.setCategoryType("IN");
            totalVo.setCategoryName("小计：");
            totalVo.setAmount(list.stream().map(FmsReportVO::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add));
            totalList.add(totalVo);
        });
        vos.addAll(totalList);
        vos.sort(Comparator.comparing(FmsReportVO::getStoreId).thenComparing(FmsReportVO::getCategoryId));
        return Result.ok(vos);
    }

}
